package com.scpii.universal.util;

import java.util.concurrent.TimeoutException;

/**
 * 超时线程控制类
 * 
 * @yuejunyan
 */
public class TimeoutThread implements Runnable {

	private Runnable task;
	private long timeout;

	public TimeoutThread(Runnable task, long timeout) {
		this.task = task;
		this.timeout = timeout;
	}

	@Override
	public void run() {
		try {
			execute(task, timeout);
		} catch (TimeoutException e) {
			// e.printStackTrace();
		}
	}

	private final void execute(Runnable task, long timeout)
			throws TimeoutException {

		Thread thread;
		if (task instanceof Thread) {
			thread = (Thread) task;
		} else {
			thread = new Thread(task);
		}
		thread.setDaemon(true);
		thread.start();
		try {
			thread.join(timeout);
		} catch (InterruptedException e) {
			/* if somebody interrupts us he knows what he is doing */
		}

		if (thread.isAlive()) {
			thread.interrupt(); // 中断执行线程
			throw new TimeoutException();
		}
	}

}
